from django.http import Http404
from django.utils.translation import ugettext_lazy as _
from treemenus.models import Menu, MenuItem

from admin import register_admin, default_fieldsets
from models import AbstractMenuItem
from urls import make_urlpatterns


def make_get_content_page(cp_model):
    """get_contentpage() function creator"""
    
    def items_from_menu(menu_name):
        return cp_model.objects.filter(menu_item__menu__name=menuname)
    
    def get_contentpage(path, menu_names=[]):
        for subset in (menu_names and map(items_from_menu, menu_names) or [cp_model.objects]):
            #by_url = subset.filter(menu_item__url=path).order_by('-level')
            by_url = subset.filter(menu_item__url=path)
            by_named_url = (cp for cp in subset.exclude(menu_item__named_url='') if cp.url == path)
            menu_items = list(by_url) or list(by_named_url)
            if menu_items:
                return menu_items[0]                
        raise Http404, 'Content page for path %s doesnt exists' % path

    return get_contentpage
